package com.yanftch.stopcoding.test
import com.yanftch.stopcoding.common.util.LogUtil
import okhttp3.OkHttpClient
import okhttp3.Request
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.IOException
import javax.imageio.ImageIO
import javax.swing.ImageIcon
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.SwingUtilities

fun loadImage(url: String): BufferedImage? {
     val TAG = "debug_"
    val client = OkHttpClient()
    val request = Request.Builder().url(url).build()

    return try {
        val response = client.newCall(request).execute()
        if (response.isSuccessful) {
            // 获取重定向后的 URL
            val realUrl = response.request.url.toString()
            LogUtil.d(TAG, "loadImage: realUrl = $realUrl")
            response.body?.byteStream()?.use { inputStream ->
                ImageIO.read(inputStream)
            }
        } else {
            null
        }
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}

// 使用示例
val imageUrl = "https://cdn.seovx.com/?mom=302"


fun main() {
    // 创建JFrame
    val frame = JFrame("Centered Labels Example")
    frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
    frame.setSize(400, 200)
    frame.foreground = Color.GRAY

    // 创建并添加自定义的JPanel
    val panel = TestView("Label 1", "Label 2")
    frame.add(panel)
    val image: BufferedImage? = loadImage(imageUrl)

    SwingUtilities.invokeLater {
        val label = JLabel(ImageIcon(image))
        frame.add(label)
    }

    // 显示窗口
    frame.isVisible = true
}
